package com.example.my2lcache.impl.caffeine;

import com.example.my2lcache.Cache;
import com.example.my2lcache.domain.CacheValue;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * caffeine cache
 *
 * @author huhao
 */
public class CaffeineCache implements Cache {
    private static final Logger logger = LoggerFactory.getLogger(CaffeineCache.class);

    private final com.github.benmanes.caffeine.cache.Cache<String, CacheValue> cache;

    /**
     * caffeine cache
     *
     * @param maxSize          存储值的最大数量
     * @param expireAfterWrite 过期时间，仅控制本地缓存数据同步
     * @param timeUnit         时间单位
     */
    public CaffeineCache(int maxSize, long expireAfterWrite, TimeUnit timeUnit) {
        this.cache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireAfterWrite, timeUnit)
                .build();
    }

    @Override
    public void set(String key, CacheValue cacheValue) {
        cache.put(key, cacheValue);
    }

    @Override
    public CacheValue get(String key) {
        return cache.getIfPresent(key);
    }

    @Override
    public void del(String key) {
        cache.invalidate(key);
    }

    @Override
    public Boolean exists(String key) {
        CacheValue cacheValue = get(key);
        return cacheValue == null ? null : (cacheValue.getValue() != null && cacheValue.isValid());
    }
}
